package com.tju.serviceOrder.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tju.JwtUtils;
import com.tju.Result;
import com.tju.serviceHandler.GuliException;
import com.tju.serviceOrder.client.EduClient;
import com.tju.serviceOrder.client.UcenterClient;
import com.tju.serviceOrder.entity.Order;
import com.tju.serviceOrder.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author gsc
 * @since 2022-01-18
 */
@RestController
@CrossOrigin
@RequestMapping("/serviceOrder/order")
public class OrderController {

    @Autowired
    private OrderService orderService;



    //生成订单方法
    @PostMapping("createOrder/{courseId}")
    public Result saveOrder(@PathVariable String courseId, HttpServletRequest request){
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        if (StringUtils.isEmpty(memberId)){
            throw new GuliException(20001,"请登录后观看");
        }
        String orderNo = orderService.createOrder(courseId,memberId);
        return Result.ok().data("orderNo",orderNo);
    }

    //根据订单id查询订单信息
    @GetMapping("getOrderInfo/{orderId}")
    public Result getOrderInfo(@PathVariable String orderId){
        System.out.println(orderId);
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no",orderId);
        Order order = orderService.getOne(wrapper);
        return Result.ok().data("item",order);
    }

    //根据课程id和用户id查询订单，看是否已经购买课程
    @GetMapping("isBuyCourse/{courseId}/{memberId}")
    public boolean isBuyCourse(@PathVariable String courseId,
                               @PathVariable String memberId){
        if (StringUtils.isEmpty(memberId)){
            return false;
        }
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",courseId);
        wrapper.eq("member_id",memberId);
        wrapper.eq("status",1);
        int count = orderService.count(wrapper);
        return count > 0;//等于0说明还未购买，否则已经购买
    }



}

